import { merge } from 'lodash-es';

export class MarkerLayer {
  constructor(map, option = {}) {
    const opt = {
      maxZoom: 17,
      gridSize: 80,
    };
    let readyResolve = null;
    this.map = map;
    this.option = merge(opt, option, {
      /* 这里需要写成箭头函数，否则 this.renderClusterMarker 内的this指向会不正确*/
      renderClusterMarker: (context) => this.renderClusterMarker(context), // 自定义聚合点样式
      // renderMarker: (context) => this.renderMarker(context), // 自定义非聚合点样式--只适用AMap v2.0
    });
    this.ready = new Promise((resolve) => {
      readyResolve = resolve;
    });
    this.createLayer().then(() => {
      readyResolve();
      readyResolve = null;
    });
  }
  loadPlugin() {
    return new Promise((resolve) => {
      if (AMap.MarkerClusterer) {
        return resolve();
      }
      AMap.plugin(['AMap.MarkerClusterer'], () => {
        return resolve();
      });
    });
  }
  async createLayer() {
    await this.loadPlugin();
    if (!this.layer) {
      this.layer = new AMap.MarkerClusterer(this.map, [], this.option);
    }
  }
  async getLayer() {
    await this.ready;
    return this.layer;
  }
  async clearLayer() {
    const layer = await this.getLayer();
    layer.clearMarkers();
    layer.setMap(null);
  }
  async renderClusterMarker(context) {
    // console.log("renderClusterMarker: ", context);
    const marker = await this.getClusterMarker(context);
    context.marker.setOffset(marker.offset);
    context.marker.setContent(marker.content);
  }
  async getClusterMarker(context) {
    const layer = await this.getLayer();
    const count = layer.getClustersCount();
    const size = Math.round(20 + Math.pow(context.count / count, 1 / 5) * 20);
    const bgColor = 'rgba(97,160,168,0.7)';
    const borderColor = 'rgba(97,160,168,0.9)';
    const shadowColor = 'rgba(75,206,217,0.7)';
    const div = document.createElement('div');
    div.style.width = div.style.height = size + 'px';
    div.style.backgroundColor = bgColor;
    div.style.border = '1px solid ' + borderColor;
    div.style.boxShadow = '0 0 5px ' + shadowColor;
    div.style.borderRadius = size / 2 + 'px';
    div.style.lineHeight = size + 'px';
    div.style.textAlign = 'center';
    div.style.fontSize = '14px';
    div.style.color = '#fff';
    div.innerHTML = context.count;
    return {
      content: div,
      offset: new AMap.Pixel(-size / 2, -size / 2),
    };
  }
  destroy() {
    this.clearLayer().catch();
  }
}
